<?php
/**
 * Loads a cache engine object
 *
 * @param string $name
 * @param array $options
 * @param boolean $useClassName
 * @return Vega_Cache_Engine_Abstract
 */
function initCacheEngine($name, $options = array(), $useClassName = false)
{
    static $registry = array();

    if (!$useClassName)
    {
        $name = strtolower($name);
        switch ($name)
        {
            case 'memcached':
                $class = 'Vega_Cache_Engine_Memcached';
                break;
            default:
                $class = 'Vega_Cache_Engine_File';
                break;
        }
    }
    else
    {
        $class = $name;
    }

    $registryKey = md5($class . serialize($options));

    if (isset($registry[$registryKey]))
    {
        return $registry[$registryKey];
    }

    $path = str_replace('_', DIRECTORY_SEPARATOR, $class);
    require_once $path . '.php';

    if (!class_exists($class))
    {
        return false;
    }

    if (empty($options))
    {
        $options = initCacheEngineDefaultOptions($class);
    }

    $object = new $class($options);
    $registry[$registryKey] = $object;
    return $object;
}

/**
 * Init default cache engine options.
 * Used by initCacheEngine()
 *
 * @param string $class
 * @param array $options
 * @return array
 */
function initCacheEngineDefaultOptions($class, $options = array())
{
    $app = Vega_App::getInstance();

    $defaultOptions = array();

    switch ($class)
    {
        case 'Vega_Cache_Engine_Memcached':
            $defaultOptions = $app->coreConfig['memcache']['server'];
            $defaultOptions['lifetime'] = 15;
            break;

        case 'Vega_Cache_Engine_File':
            $defaultOptions = array('cache_dir' => $app->getRootPath() . DIRECTORY_SEPARATOR . 'app' .
                DIRECTORY_SEPARATOR . $app->getAppName() . DIRECTORY_SEPARATOR . 'writeable' . DIRECTORY_SEPARATOR . 'cache', 'lifetime' => 15, 'index_level' => 2);
            break;
    }

    return array_merge($defaultOptions, $options);
}